<?php
class FT_Events {
	private $info = array();
	private $data = array();
	
	/* CONSTRUCTOR */
	
	function FT_Events() {
		if($this->FT_Crear_Tabla_Asistentes_Eventos()) :
			//$this->FT_Hooks();
			//$this->FT_CSS_JS();
		endif;
	}
	
	/* METODOS PRIVADOS */
	
	/* Crea la tabla en la base de datos con las confirmaciones de asistencia de los usuarios, si es que esta no existe */
	
	private function FT_Crear_Tabla_Asistentes_Eventos() {
		$table_name = 'ft_events';
		
		$sql = array(
			"event_id int(12) NOT NULL",
		  	"user_id int(12) NOT NULL",
			"status varchar(10) NOT NULL",
			"PRIMARY KEY (event_id)"
		);
		
		return FT_Crear_Tabla($table_name, $sql);
	}
	
	/* Genera los Hooks requeridos */
	
	private function FT_Hooks() {
		add_action('admin_menu', array($this, 'FT_Anexar_Formulario_Admin'));
		add_action('save_post', array($this, 'FT_Guardar_Formulario_Admin'));
		add_action('admin_footer', array($this, 'FT_Is_Event_JS'));
	}
	
	private function FT_CSS_JS() {
		$css = array(
			array(
				'nombre' => 'ft_events-css',
				'src' => FT_PLUGIN_URL.'/css/events.css'
			)
		);
		
		$js = array(
			array(
				'nombre' => 'ft_events-js',
				'src' => FT_PLUGIN_URL.'/js/events.js',
				'dependencia' => array('jquery')
			)
		);
		
		if(FT_Es_URL('blog-admin')) :
			$js_admin = array(
				array(
					'nombre' => 'ft_date-js',
					'src' => FT_PLUGIN_URL.'/js/date.js',
					'dependencia' => array('jquery')
				),
				array(
					'nombre' => 'ft_calendar-js',
					'src' => FT_PLUGIN_URL.'/js/calendar.js',
					'dependencia' => array('jquery')
				),
				array(
					'nombre' => 'ft_hours-js',
					'src' => FT_PLUGIN_URL.'/js/hours.js',
					'dependencia' => array('jquery')
				)
			);
			
			$js = array_merge($js_admin, $js);
		endif;
		
		FT_Agregar_CSS_JS($css, $js);
	}
	
	/* Genera los valores de los campos del formulario */
	
	private function FT_Crear_Data() {
		$info_extras = FT_Info('post-extra'); 
		$this->data = $info_extras['ft-events'];
			
		if($this->data != '' && !empty($this->data)) :
			$this->data['start-date'] = date('d/m/Y', strtotime($this->data['start-date']));
			$this->data['start-hour'] = date('H:i', strtotime($this->data['start-hour']));
			$this->data['end-date'] = date('d/m/Y', strtotime($this->data['end-date']));
			$this->data['end-hour'] = date('H:i', strtotime($this->data['end-hour']));
		endif;
	}
	
	/* METODOS PUBLICOS */
	
	/* Crea un Javascript que indica si el post actual es un evento o no */
	
	public function FT_Is_Event_JS() {
		$is_event = 'false';
		$cat_id = get_cat_id('Eventos');
		
		if($this->info['event']) :
			$is_event = 'true';
			$cat_id = $this->info['cat_id'];
		endif;
			
		?>
			<script type="text/javascript">
				var is_event = <?php echo $is_event; ?>;
				var cat_id = <?php echo $cat_id; ?>;
			</script>
		<?php		
	}
	
	/* Anexa el formulario en una caja en la administracion */
	
	public function FT_Anexar_Formulario_Admin() {
		add_meta_box('ft-events', __('Datos del evento', 'firsttuesday'), array($this, 'FT_Crear_Formulario_Admin') , 'post', 'normal', 'high');
	}

	/* Crea el formulario con los campos de datos del evento */
	
	public function FT_Crear_Formulario_Admin() {
		//$this->FT_Crear_Data();
?>
		<p>
			<?php _e('Ingresa los datos específicos del evento. Una vez que hayas guardado el post, automáticamente se notificará a los usuarios del blog. Adicionalmente, y si lo deseas, puedes invitar a otros usuarios que no pertenezcan al blog.', 'firsttuesday'); ?> <a href="#" title="<?php _e('Invitar a usuarios de otros blogs', 'firsttuesday'); ?>" class="ligth-box" id="add-users-link"><?php _e('Invitar a usuarios de otros blogs', 'firsttuesday'); ?></a>.
		</p>
		<p>
			<label for="place">
				<?php _e('Lugar', 'firsttuesday'); ?>:
			</label>
			<input type="text" id="place" name="place" class="event-place event-input" value="<?php echo $this->data['place']; ?>"/>
		</p>
		<div id="start-data">
			<h2>
				<?php _e('Inicio', 'firsttuesday'); ?>
			</h2>
			<p>
				<?php _e('Fecha', 'firsttuesday'); ?>:
				<span id="start-date-value" class="event-value"><?php echo $this->data['start-date']; ?></span>
				<input type="text" id="start-date" name="start-date" class="event-date event-input" value="<?php echo $this->data['start-date']; ?>"/>
			</p>
			<p>
				<?php _e('Hora', 'firsttuesday'); ?>:
				<span id="start-hour-value" class="event-value"><?php echo $this->data['start-hour']; ?></span>
				<input type="text" id="start-hour" name="start-hour" class="event-hour event-input" value="<?php echo $this->data['start-hour']; ?>"/>
				<a href="#" class="event-hour-picker" id="start-hour-picker"></a>
			</p>
		</div>
		<div id="end-data">
			<h2>
				<?php _e('Término', 'firsttuesday'); ?>
			</h2>
			<p>
				<?php _e('Fecha', 'firsttuesday'); ?>:
				<span id="end-date-value" class="event-value"><?php echo $this->data['end-date']; ?></span>
				<input type="text" id="end-date" name="end-date" class="event-date event-input" value="<?php echo $this->data['end-date']; ?>"/>
			</p>
			<p>
				<?php _e('Hora', 'firsttuesday'); ?>:
				<span id="end-hour-value" class="event-value"><?php echo $this->data['end-hour']; ?></span>
				<input type="text" id="end-hour" name="end-hour" class="event-hour event-input" value="<?php echo $this->data['end-hour']; ?>"/>
				<a href="#" class="event-hour-picker" id="end-hour-picker"></a>
			</p>
		</div>
		<input type="hidden" id="security-check" name="security-check" value="<?php echo wp_create_nonce(plugin_basename(__FILE__)); ?>"/>
<?php
	}
	
	/* Guarda los valores de los campos del formulario en la base de datos */
	
	public function FT_Guardar_Formulario_Admin($post_id) {
		if((!wp_verify_nonce($_POST['security-check'], plugin_basename(__FILE__)) || ($_POST['post_type'] != 'post') || !current_user_can('edit_post', $post_id) || !FT_Info('current')) || (($_POST['place'] == '') && ($_POST['start-date'] == '') && ($_POST['start-hour'] == '') && ($_POST['end-date'] == '') && ($_POST['end-hour'] == ''))) :
			delete_post_meta($post_id, 'ft-events');
			return $post_id;
		endif;
				
		$new_data_aux['place'] = $_POST['place'];
		if($_POST['start-date'] != '')
			$new_data_aux['start-date'] = date('Y-m-d', strtotime(str_replace('/', '-', $_POST['start-date'])));
		if($_POST['start-hour'] != '')
			$new_data_aux['start-hour'] = $_POST['start-hour'].':00';
		if($_POST['end-date'] != '')
			$new_data_aux['end-date'] = date('Y-m-d', strtotime(str_replace('/', '-', $_POST['end-date'])));
		if($_POST['end-hour'] != '')
			$new_data_aux['end-hour'] = $_POST['end-hour'].':00';
			
		$new_data = FT_Serialize($new_data_aux);
		
		$prev_data = $this->FT_Get_Data();
			
		if($prev_data == '')
			add_post_meta($post_id, 'ft-events', $new_data, true);
		elseif($new_data != $prev_data)
			update_post_meta($post_id, 'ft-events', $new_data);
			
		return $post_id;
	}
}


?>